package com.hopes.bizz.poll.job;

import com.hopes.bizz.common.core.util.DateUtils;
import com.hopes.bizz.poll.common.constant.MonitorConstant;
import com.hopes.bizz.poll.common.constant.MonitorDataTypeEnum;
import com.hopes.bizz.poll.om.entity.PollAnalyStatisticTimeEntity;
import com.hopes.bizz.poll.om.service.PollAnalyStatisticTimeService;
import com.hopes.bizz.poll.om.service.PollMonthService;
import com.hopes.bizz.poll.om.service.PollYearService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/10/10 10:19
 * @Description:
 */
@Service
@Slf4j
public class DataStatisticsJobService {

    @Autowired
    private PollMonthService pollMonthService;
    @Autowired
    private PollYearService pollYearService;
    @Autowired
    private PollAnalyStatisticTimeService pollAnalyStatisticTimeService;


    @XxlJob("dataStatisticsJobHandler")
    public void dataStatisticsJobHandler() {
        long start = System.currentTimeMillis();
        log.info("----------------月、年报表统计中----------------`");
        // size为一次计算的天数
        int size = 100;
        for (int i = 0; i < size; i++) {
            boolean next = statisticMonthData();
            if (!next) {
                break;
            }
        }
        log.info("----------------月、年报表统计结束,结果为={},耗时(毫秒)={}----------------`", true, System.currentTimeMillis() - start);
        // 设置任务结果
        XxlJobHelper.handleSuccess();
    }

    private boolean statisticMonthData() {
        // # 获取当前待统计的监测数据类型及时间
        PollAnalyStatisticTimeEntity statisticTime = pollAnalyStatisticTimeService.getByDataType(MonitorDataTypeEnum.day);
        // ## 如果不存在响应记录，则新建一条
        if (statisticTime == null) {
            pollAnalyStatisticTimeService.createDayStatisticTask();
            return true;
        }
        Date now = new Date();
        Date analyTime = statisticTime.getAnalyTime();
        // ## 如果当前时间大于待统计时间，则开始统计
        if (now.compareTo(analyTime) > 0) {
            Date time = DateUtils.addDate(analyTime, -1);
            Date beginTime = DateUtils.getDateStart(time);
            Date endTime = DateUtils.getDateEnd(time);
            Date monthBegin = DateUtils.set(beginTime, Calendar.DAY_OF_MONTH, 1);
            // 触发月数据统计
            pollMonthService.batchStatisticMonitorData(monthBegin, endTime);
            Date yearBegin = DateUtils.set(monthBegin, Calendar.MONTH, 0);
            // 月数据统计完成触发年数据统计
            pollYearService.batchStatisticMonitorData(yearBegin, endTime);
            statisticTime.setAnalyTime(DateUtils.addDate(analyTime, MonitorConstant.ONE));
            pollAnalyStatisticTimeService.updateById(statisticTime);
            return true;
        }
        return false;
    }
}
